import React from 'react';
import ReactDOM from 'react-dom';
import classnames from 'classnames';

export default class view extends React.Component {
    static propTypes = {
        header: React.PropTypes.element.isRequired,
        content: React.PropTypes.element.isRequired,
        className: React.PropTypes.string,
        isShow: React.PropTypes.bool,
        onChange: React.PropTypes.func
    };

    static defaultProps = {
        isShow: false
    }

    constructor(props, context) {

        super(props, context);
        // init state;
        this.state = {
            isShow:props.isShow
        };
    }

    componentWillMount() {
        this._isMounted = true;

    }

    componentDidMount() {
        if (this.state.isShow) {
            document.addEventListener('click', this.handleDocumentClick, false);
        }
    }


    handleDocumentClick = (event) => {
        if (this.state.isShow && !this.targetIsDescendant(event, ReactDOM.findDOMNode(this))) {

            this.setState({
                isShow: false
            });

            this.props.onChange && this.props.onChange(false);
            document.removeEventListener('click', this.handleDocumentClick, false);
        }
    }

    targetIsDescendant (event, parent) {
        let node = event.target;
        while (node !== null) {
            if (node === parent) return true;
            node = node.parentNode;
        }
        return false;
    }

    pauseEvent (event) {
        event.stopPropagation();
        event.preventDefault();
    }

    componentDidUpdate() {
        if (this.state.isShow) {
            document.addEventListener('click', this.handleDocumentClick, false);
        }
    }


    componentWillUnmount() {
        this._isMounted = false;
    }

    componentWillReceiveProps({isShow}) {
        this.setState({
            isShow: isShow
        });
    }

    handleToggleClick = (event) =>  {
        this.pauseEvent(event);
        var show = this.state.isShow;


        this.setState({
            isShow: !show,
            isTarget: false
        });
        this.props.onChange && this.props.onChange(!show);
    }

    render() {
        const classNames = classnames({
            'orin-sw-recombo-root': true,
            [this.props.className]: this.props.className ? true : false
        });
        let contentClassNames = classnames({
            'combo-content-box': true,
            'show': this.state.isShow
        });
        return (
            <div className={ classNames } >
                <div className="combo-header-box" onClick={ this.handleToggleClick }>
                    <div className="combo-header-content">
                        { this.props.header }
                    </div>
                    <div className="combo-header-btn"></div>
                </div>
                <div className={ contentClassNames } onClick={ e => { this.pauseEvent(e); }}>{ this.props.content }</div>
            </div>
        );
    }
}
